<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
	        <a-col :span="6" >
            <a-form-model-item label="订货批号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="mainNum">
              <a-input v-model="model.mainNum" placeholder="" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="订单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="num">
              <a-input v-model="model.num" placeholder="" readOnly :disabled="disabled"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="人员姓名" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="suspectsName">
              <a-input v-model="model.suspectsName" placeholder="" readOnly :disabled="disabled"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="证件号码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="idNum">
              <a-input v-model="model.idNum" placeholder="" readOnly :disabled="disabled"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="付款前余额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="suspectsBalance">
              <a-input v-model="model.suspectsBalance" placeholder="" readOnly :disabled="disabled"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="监室号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="orgCode">
              <j-select-depart v-model="model.orgCode" multi disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="订单月份" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="orderMonth">
              <a-input v-model="model.orderMonth" placeholder="" readOnly :disabled="disabled"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="订单类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="orderType">
              <j-dict-select-tag type="list" v-model="model.orderType" dictCode="order_type" placeholder="请选择订单类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="商品总额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="goodsTotal">
              <a-input-number v-model="model.goodsTotal" placeholder="" style="width: 100%" disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="其他费用" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="otherFee">
              <a-input-number v-model="model.otherFee" placeholder="请输入其他费用" style="width: 100%" @change="handleChange"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="优惠费用" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="discountFee">
              <a-input-number v-model="model.discountFee" placeholder="请输入优惠费用" style="width: 100%" @change="handleChange"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="食品费用" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="foodFee">
              <a-input-number v-model="model.foodFee" placeholder="" style="width: 100%" disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="实际支付" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="actualPayment">
              <a-input-number v-model="model.actualPayment" placeholder="" style="width: 100%" disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="下单时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="orderTime">
              <j-date placeholder="" v-model="model.orderTime" style="width: 100%" disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="订单状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="orderState">
              <j-dict-select-tag type="list" v-model="model.orderState" dictCode="order_status" placeholder="" disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="suspectsId">
              <a-input v-model="model.suspectsId" type="hidden" placeholder="" readOnly :disabled="disabled"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="订单备注" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="orderNotes">
              <a-textarea v-model="model.orderNotes" rows="3" placeholder="" />
            </a-form-model-item>
          </a-col>
	        <a-col :span="12" >
            <a-form-model-item label="订单校验" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="orderCheck">
              <a-textarea v-model="model.orderCheck" rows="3" placeholder="" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="订单明细表" :key="refKeys[0]" :forceRender="true">
        <j-editable-table
          :ref="refKeys[0]"
          :loading="fpmsOrderItemTable.loading"
          :columns="fpmsOrderItemTable.columns"
          :dataSource="fpmsOrderItemTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true">
          <template v-slot:num="props">
            <a-input-number
              :min="0" :max="1000"
              :value="props.text"
              @change="(event) => handleProChange(event, props)"
            >
            </a-input-number>
          </template>
        </j-editable-table>
      </a-tab-pane>
      <a-tab-pane tab="订单日志表" :key="refKeys[1]" :forceRender="true">
        <j-editable-table
          :ref="refKeys[1]"
          :loading="fpmsOrderLogTable.loading"
          :columns="fpmsOrderLogTable.columns"
          :dataSource="fpmsOrderLogTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true"/>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>

  import { getAction } from '@/api/manage'
  import { FormTypes,getRefPromise,VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
  import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
  import { validateDuplicateValue } from '@/utils/util'

  import { httpAction, putAction } from '@/api/manage'
  import { JEditableTable } from '@/components/jeecg/JEditableTable'

  const ruleBaseURL = '/sys/fillRule/executeRuleByCode/'

  export default {
    name: 'FpmsOrderForm',
    mixins: [JEditableTableModelMixin],
    components: {
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 3 },
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
        model:{
            // orderType:"6",
            actualPayment:0,
        },
        form: this.$form.createForm(this),
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 0,
        validatorRules: {
          num: [
            { required: true, message: '请输入订单号!'},
          ],
          name: [
            { required: true, message: '请输入姓名!'},
          ],
          orderType: [
            { required: true, message: '请选择订购类型!'},
          ]
        },
        refKeys: ['fpmsOrderItem', 'fpmsOrderLog', ],
        tableKeys:['fpmsOrderItem', 'fpmsOrderLog', ],
        activeKey: 'fpmsOrderItem',
        // 订单明细表
        fpmsOrderItemTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '商品名称',
              key: 'name',
              //type: FormTypes.inputNumber,
              //disabled:false,
              type: FormTypes.popup,
              popupCode:"fpms_goods_list",
              destFields:"goodsId,name,price,type",
              orgFields:"id,name,price,type",
              width:"330px",
              placeholder: '请选择商品',
              defaultValue:'',
            },
            {
              title: '商品单价',
              key: 'price',
              type: FormTypes.inputNumber,
              disabled:true,
              width:"200px",
              placeholder: '',
              defaultValue:'',
            },
            {
              title: '商品数量',
              key: 'num',
              type: FormTypes.slot,
              slotName: 'num',
              width:"100px",
              // placeholder: '请输入${title}',
              defaultValue:'0',
              
            },
            {
              title: '商品总金额',
              key: 'amount',
              type: FormTypes.inputNumber,
              statistics: false,
              disabled:false,
              width:"200px",
              placeholder: '',
              defaultValue:'',
            },
            {
              title: '商品ID',
              key: 'goodsId',
              type:"hidden"
            },
            {
              title: '商品类型',
              key: 'type',
              type: "hidden",
            },
          ]
        },
        // 订单日志表
        fpmsOrderLogTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '操作人',
              key: 'createBy',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '操作日期',
              key: 'createTime',
              type: FormTypes.datetime,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '订单id',
              key: 'orderId',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '订单状态变更',
              key: 'orderState',
              type: FormTypes.select,
              dictCode:"order_status",
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
          ]
        },
        url: {
          add: "/order/fpmsOrder/add",
          edit: "/order/fpmsOrder/edit",
          queryById: "/order/fpmsOrder/queryById",
          fpmsOrderItem: {
            list: '/order/fpmsOrder/queryFpmsOrderItemByMainId',
            initList: '/order/fpmsOrder/initFpmsOrderItem'
          },
          fpmsOrderLog: {
            list: '/order/fpmsOrder/queryFpmsOrderLogByMainId'
          },
          rule: {
            orderNum: ruleBaseURL + 'order_num'
          },
        },
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },      
    },
    created () {

    },
    methods: {
      addBefore(){
        this.fpmsOrderItemTable.dataSource=[]
        this.fpmsOrderLogTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })

        this.getNum(this.model); 

        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.fpmsOrderItem.list, params, this.fpmsOrderItemTable)
          this.requestSubTableData(this.url.fpmsOrderLog.list, params, this.fpmsOrderLogTable)
        }else{
          this.requestSubTableData(this.url.fpmsOrderItem.initList, '', this.fpmsOrderItemTable)
        }
      },
      //校验所有一对一子表表单
      validateSubForm(allValues){
          return new Promise((resolve,reject)=>{
            Promise.all([
            ]).then(() => {
              resolve(allValues)
            }).catch(e => {
              if (e.error === VALIDATE_NO_PASSED) {
                // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
              } else {
                console.error(e)
              }
            })
          })
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          fpmsOrderItemList: allValues.tablesValue[0].values,
          fpmsOrderLogList: allValues.tablesValue[1].values,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },

      // getNum() {
      //   return new Promise((resolve,reject)=>{
      //     putAction(this.url.rule.orderNum).then(res => {
      //       // 执行成功，获取返回的值，并赋到页面上
      //       console.log("result:", res);
      //       if (res.success) {
      //         // record.num = res.result;
      //         return res.result;
      //         resolve()
      //       }else{
      //         reject()
      //       }
      //     })
      //   })       
      // },
      getNum(record) {
        putAction(this.url.rule.orderNum, this.model).then(res => {
          // 执行成功，获取返回的值，并赋到页面上
          console.log("result:", res);
          if (res.success) {
            record.num = res.result;
            this.model = Object.assign({}, record);     
            this.visible = true;  
          }
        })
      },
      
      handleProChange(event, props) {
        // 参数解释
        // props.index ：当前行的下标
        // props.text ：当前值，可能是defaultValue定义的值，也可能是从dataSource中取出的值
        // props.rowId ：当前选中行的id，如果是新增行则是临时id
        // props.column ：当前操作的列
        // props.getValue ：这是一个function，执行后可以获取当前行的所有值（禁止在template中使用）
        //                  例：const value = props.getValue()
        // props.target ：触发当前事件的实例，可直接调用该实例内的方法（禁止在template中使用）
        //                  例：target.add()
        let { index, rowId, target, text } = props;
        console.log('text:',text);

        // let items;
        // target.getValues((error, values) => {
        //   console.log('values:', values)
        //   items = values;
        // })

        //console.log('item:',target.getValuesSync(rowId));
        let items = target.getValuesSync({rowIds: rowId}).values;
        let item = items[index];
        //console.log('item:',item);
        let price = item.price;
        console.log('price:',price);
        console.log('event:',event);
        let num = event;
        console.log('num:',num);
        let nval = (price*num).toFixed(2);
        target.setValues([
          {
            rowKey: rowId, // 行的id
            values: { // 在这里 values 中的 name 是你 columns 中配置的 key
              'num': num,
              'amount': nval
            }
          },
        ]);

        target.getAll().then(res => {
          let count = 0;
          let foodCount = 0;
          console.log("values:", res.values);
          res.values.forEach(item => {
            let num = item['num'];
            var value = item['amount'] - 0;
            let type = item['type'];
            if (value && count !== '-' && num !== '0') {
              try {
                count += value;
                if (type == '1') {
                  foodCount += value;
                }
              } catch (e) {
                count = '-';
              }
            }
          });
          console.log("count:", count);
          // console.log("this.form:", this.form);
          // console.log("actualPayment:", this.form.getFieldsValue(actualPayment));

          this.model.goodsTotal = count.toFixed(2);
          this.form.setFieldsValue({goodsTotal:count});

          this.model.foodFee = foodCount.toFixed(2);
          this.form.setFieldsValue({foodFee:foodCount});

          let goodsTotal = this.model.goodsTotal;
          let otherFee = this.model.otherFee;
          let discountFee = this.model.discountFee;
          let actualPayment = goodsTotal + otherFee - discountFee;
          this.model.actualPayment = actualPayment.toFixed(2);
          this.form.setFieldsValue({actualPayment:actualPayment});
				});
      },

      handleChange(value){
          let goodsTotal = this.model.goodsTotal;
          let otherFee = this.model.otherFee;
          let discountFee = this.model.discountFee;
          let actualPayment = goodsTotal + otherFee - discountFee;
          this.model.actualPayment = actualPayment;
          this.form.setFieldsValue({actualPayment:actualPayment});
      },

    },

  }
</script>

<style scoped>
</style>